package com.lk.security.authentication.mobile;

import com.lk.security.authentication.CustomAuthenticationFailureHandler;
import com.lk.security.authentication.CustomAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.stereotype.Component;

/**
 * @description: 用于组合和其他关于手机登录的组件
 * @author: Aspirin
 * @create: 2020-05-31 10:56
 */
@Component
public class MobileAuthenticationConfig
    extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

  @Autowired private CustomAuthenticationFailureHandler customAuthenticationFailureHandler;
  @Autowired private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
  @Autowired private UserDetailsService mobileUserDetailService;

  @Override
  public void configure(HttpSecurity http) {

    MobileAuthenticationFilter mobileAuthenticationFilter = new MobileAuthenticationFilter();
    // 获取容器中已经存在的AuthenticationManage对象，并传入mobileAuthenticationFilter里面
    mobileAuthenticationFilter.setAuthenticationManager(
        http.getSharedObject(AuthenticationManager.class));

    // 指定记住我功能[默认实现类是NullRememberService]
    mobileAuthenticationFilter.setRememberMeServices(
        http.getSharedObject(RememberMeServices.class));

    // 这是关于session重复登录
    mobileAuthenticationFilter.setSessionAuthenticationStrategy(
        http.getSharedObject(SessionAuthenticationStrategy.class));

    mobileAuthenticationFilter.setAuthenticationSuccessHandler(customAuthenticationSuccessHandler);
    mobileAuthenticationFilter.setAuthenticationFailureHandler(customAuthenticationFailureHandler);

    // 构建一个MobileAuthentication实例，接收mobileUserDetailsService 通过手机号查询用户信息
    MobileAuthenticationProvider provider = new MobileAuthenticationProvider();
    provider.setUserDetailsService(mobileUserDetailService);

    // 将provider绑定到httpSecurity上，并将手机验证过滤器放在用户名过滤器之后
    http.authenticationProvider(provider)
        .addFilterAfter(mobileAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
  }
}
